<?php
/**
 * 场外购买处理.
 * User: madong
 * Date: 2018/10/3
 * Time: 12:16 AM
 */

namespace app\api\controller\jiaoyi;
use app\api\model\Jiaoyi;
use app\api\model\Jiaoyibuylog;
use app\api\model\JiaoyiUinfo;
use think\Controller;
use think\Db;
use think\Request;
use think\Config;

class Changwaibuy extends Controller
{
    private $Order_linit_time = 15; // 订单自动取消时间（单位/分钟）

    //处理用户买入
    public function Order_buy_dispose(){

        $Uinfo = new JiaoyiUinfo();

        $Main_Order_Obj = new Jiaoyi();

        $Jiaoyi_log_obj = new Jiaoyibuylog();

        $res = Request::instance();

        $Max = $Main_Order_Obj->where('ordernumber',$this->Jiemi($res->param('ordernumber')))->value('da');

        $Min = $Main_Order_Obj->where('ordernumber',$this->Jiemi($res->param('ordernumber')))->value('xiao');

        $U_buy_order_num = count($Jiaoyi_log_obj->where('uname',$this->Jiemi($res->param('buyname')))->where('uorderzt',0)->where('ubizhong',$res->param('bizhong'))->where('oorderzt',0)->select());//当前币种未付款的订单数

        $U_info_all = $Uinfo->where('uname',$this->Jiemi($res->param('buyname')))->find();//买方账户全部信息

        $O_info_all = $Uinfo->where('uname',$this->Jiemi($res->param('sellname')))->find();//卖方账户全部信息

        $U_balance = $Uinfo->where('uname',$this->Jiemi($res->param('buyname')))->value($res->param('bizhong'));//当前买入账户的余额

        $O_balance = $Uinfo->where('uname',$this->Jiemi($res->param('sellname')))->value($res->param('bizhong'));//当前卖出账户的余额

        $U_buy_num = ['cny'=>$res->param('cnynum'),'coin'=>$res->param('coinnum')];//购买的数量(包括人民币和货币)

        $U_name_O_name = ['buy_name'=>$this->Jiemi($res->param('buyname')),'sell_name'=>$this->Jiemi($res->param('sellname'))];//获取买方和卖方的账号

        $new_time = time();

        if ($res->isPost()){

            //如果有未付款的订单，就不能继续下单，就把下面的注释打开
            //if ($U_buy_order_num > 0){echo json_encode(['zt'=>0,'msg'=>'您前面还有'.$U_buy_order_num.'笔订单没有付款!']);die();}

            if (!$U_buy_num['coin']){echo json_encode(['zt'=>0,'msg'=>'数量不能为空']);die();}

            if ($U_buy_num['coin'] < $Min || $U_buy_num['coin'] > $Max){echo json_encode(['zt'=>0,'msg'=>'请认真检查交易限额']);die();}

            if ($U_buy_num['coin']>$O_balance){echo json_encode(['zt'=>0,'msg'=>"当前卖方账户已不足您的购买的数量\n当前卖方剩余".$res->param('bizhong').'数量为'.$O_balance]);die();}

            if ($U_name_O_name['buy_name'] == $U_name_O_name['sell_name']){echo json_encode(['zt'=>0,'msg'=>'不能购买自己的订单!']);die();}

            Db::startTrans();//打开事务

            try{

                Db::name('jiaoyibuylog')->insert([

                    'uid' => $U_info_all['uid'],//卖方账户ID

                    'uname' => $U_name_O_name['buy_name'],//买方账户

                    'unickname' => $U_info_all['unickname'],//买方昵称

                    'utruename' => $U_info_all['truename'],//买方真实姓名

                    'ucnynum' => $U_buy_num['cny'],//买方提交过来的人民币数量

                    'ucoinnum' => $U_buy_num['coin'],//买方提交过来的虚拟货币数量

                    'ubizhong' => $res->param('bizhong'),//买方购买的货币类型

                    'uordernumber' => $this->Jiemi($res->param('ordernumber')),//卖方订单编号

                    'ouordernumber' => $this->Jiemi($res->param('ordernumber')),//买方订单编号（暂时和卖方订单编号一样）后期整理数据库删除掉

                    'ordernumber' => strtoupper($res->param('bizhong')).'-'.strtoupper(md5($U_name_O_name['buy_name'].$new_time)),//生成当订单的总订单编号

                    'uorderzt' => 0,//买入状态  0为买入  1卖出 这个也是暂定

                    'ubeizhu' => $U_name_O_name['buy_name'].'买入'.$U_buy_num['coin'].'个'.$res->param('bizhong').'花费人民币'.$U_buy_num['cny'],//当前订单的说明

                    'zfbzh' => $O_info_all['zhifubaoaccount'],//卖方支付宝账号

                    'zfbimg' => $O_info_all['zhifubaoimg'],//卖方支付宝二维码

                    'wxzh' => $O_info_all['weixinaccount'],//卖方微信账户

                    'wximg' => $O_info_all['weixinimg'],//卖方微信二维码

                    'ylzh' => $O_info_all['bankname'],//卖方银行账号

                    'ylname' => $O_info_all['bankkaihu'],//卖方银行开户行名称

                    'yladdr' => $O_info_all['bankkaihuaddr'],//卖方银行开户行地址

                    'oid' => $O_info_all['uid'],//卖方UID

                    'oname' => $U_name_O_name['sell_name'],//卖方用户名

                    'otruename' => $O_info_all['truename'],//卖方真实姓名

                    'onickname' => $O_info_all['unickname'],//卖方昵称

                    'time' => $new_time,//订单生成时间

                    'dqsj' => $this->Order_linit_time,//当前订单的取消时间

                    'chengjiaojiage' => $res->param('chengjiaojiage')//成交价格


                ]);

                Db::name('jiaoyi')->where('ordernumber',$this->Jiemi($res->param('ordernumber')))->setInc('wfkdd',1);//给卖方订单里未付款数量加1

                Db::name('jiaoyi_uinfo')->where('uname',$U_name_O_name['sell_name'])->setDec($res->param('bizhong'),$U_buy_num['coin']);//卖出的用户减去相应的货币数量

                Db::name('jiaoyi_uinfo')->where('uname',$U_name_O_name['sell_name'])->setInc('d'.$res->param('bizhong'),$U_buy_num['coin']);//卖出的冻结加上相应的货币数量

                //冻结信息添加冻结表
                Db::name('jiaoyidj')->insert([

                    'uid' => $O_info_all['uid'],//被冻结的用户ID  卖方

                    'uname' => $U_name_O_name['sell_name'],//被冻结的用户ID  卖方

                    'oid' => $O_info_all['uid'],//对方id 买方

                    'oname' => $U_name_O_name['buy_name'],//对方账户 买方

                    'bizhong' => $res->param('bizhong'),//冻结币种

                    'ddhao' => strtoupper($res->param('bizhong')).'-'.strtoupper(md5($U_name_O_name['buy_name'].$new_time)),//当前订单编号

                    'oddhao' => $this->Jiemi($res->param('ordernumber')),//对方订单编号

                    'djnum' => $U_buy_num['coin'],//冻结数量

                    'djcnynum' => $U_buy_num['cny'],//人民币数量

                    'djqnum' => $O_balance,//冻结钱余额

                    'djhnum' => $O_balance-$U_buy_num['coin'],//冻结后余额

                    'djtype' => 0,//0买入 1卖出

                    'djnote' => $U_name_O_name['buy_name'].'购买用户'.$U_name_O_name['sell_name'].$res->param('bizhong').'数量'.$U_buy_num['coin'],//说明

                    'djzt' => 0,//冻结状态 0冻结  1释放

                    'time' => $new_time//冻结时间

                ]);

                Db::commit();//提交事务

                echo json_encode(['zt'=>1,'msg'=>'买入成功,请尽快付款!']);

            }catch (\Exception $e){

                echo json_encode(['zt'=>0,'msg'=>'买入失败,稍后重试!']);

                Db::rollback();//事务回滚

            }

        }else{

            echo json_encode(['zt'=>2,'msg'=>'error']);

        }

    }
    //获取下单完成的订单传给前端
    public function Get_new_order($uname){

        $jiaoyilogobj = new Jiaoyibuylog();

        $res = $jiaoyilogobj->where('uname',$uname)->order('id desc')->find();

        if ($res){

            echo json_encode(['zt' =>1,'msg'=>$res]);

        }else{

            echo json_encode(['zt'=>0,'msg'=>'加载失败请到订单管理付款']);

        }

    }
    //确认付款
    public function Get_fukuan(){

        $res = Request::instance();

        if ($res->isPost()){

            if ($res->param('id') && $res->param('ordernumber')){

                if (!$res->param('zhifu')==0){

                    Db::startTrans();

                    try{

                        Db::name('jiaoyibuylog')->where('id',$res->param('id'))->where('ordernumber',$res->param('ordernumber'))->update([

                            'oorderzt' => 1,

                            'ofukuanfs' => $res->param('zhifu'),

                            'fktime' => time()

                        ]);

                        Db::name('jiaoyi')->where('ordernumber',$res->param('urdernumber'))->setInc('yfkdd',1);

                        Db::name('jiaoyi')->where('ordernumber',$res->param('urdernumber'))->setDec('wfkdd',1);

                        echo json_encode(['zt'=>1,'msg'=>'操作成功,等待对方确认','data'=>1]);

                        Db::commit();

                    } catch (\Exception $e) {

                        echo json_encode(['zt'=>0,'msg'=>'未能查询到此订单!']);

                        Db::rollback();
                    }


                }else{

                    echo json_encode(['zt'=>0,'msg'=>'请选择支付方式']);

                }

            }else{

                echo json_encode(['zt'=>0,'msg'=>'订单错误!']);

            }

        }else{

            echo json_encode(['zt'=>2,'msg'=>'error']);

        }

    }

    //数据解密
    private function Jiemi($data){

        $jiami_data = openssl_decrypt(base64_decode($data,false),"AES-128-CBC",Config::get('Key'),OPENSSL_RAW_DATA,Config::get('IV'));

        return $jiami_data;

    }
    //数据加密
    private function Jiami($data){

        $jiemi_data =  base64_encode(openssl_encrypt($data,"AES-128-CBC",Config::get('Key'),OPENSSL_RAW_DATA,Config::get('IV')));

        return $jiemi_data;

    }

}